import styled from 'styled-components'
import Controller from '../../component/Controller'
import { useTranslation } from 'react-i18next'
import Item from './Item'
import { useCallback, useEffect, useMemo, useState } from 'react'
import Message from '../../component/Message'
import Icon from '../../component/Icon'
import { wallet } from '../../service'
import { useDispatch } from 'react-redux'
import { updateInfo } from '../../reducer/userReducer'
import WalletBg from '../../asserts/wallet_bg.png'
import User from './User'
import IconBg from '../../asserts/icon_bg.webp'
import { isIOS } from '../../utils/check'
import { formatBase64Image } from '../../utils/common'
import Loading from '../../component/Loading'
import { useNavigate } from '../../hook/navigate'
import { Router } from '../../router'
import { SwitchConfigKeys } from '../../utils/switch'
import useSwitch from '../../hook/switch'
import Trade from './Trade'

const Container = styled(Controller)`
    background-color: ${(prop) => prop.theme.background.normal};
`

const Title = styled.span`
    font-size: 18px;
    font-weight: 500;
    color: #ffffff;
`

const Header = styled.div`
    padding: 0 1rem;
    box-sizing: border-box;
    margin-top: 1.3125rem;
`

const ItemBox = styled(Item) <{ $bg: string }>`
    background: ${({ $bg }) => `url(${$bg}) no-repeat no-repeat center;`};
    background-size: cover;
`

const BalanceBox = styled.div`
    background: linear-gradient(90deg, #0041FD 0%, #006FFF 100%);
    border-radius: 10px;
    overflow: hidden;
    margin-top: .5rem;
`

const WithDrawBox = styled.div`
    width: 100%;
    height: 46px;
    background-color: #0A4BD0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 .75rem 0 1rem;
    box-sizing: border-box;
`

const WithDraw = styled.div`
    background: ${(prop) => prop.theme.modal.confirm_bg};
    padding: .4375rem 1.5rem;
    box-sizing: border-box;
    line-height: .8125rem;
    border-radius: .8125rem;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: .875rem;
    color: white;
`

const TonBox = styled.div`
    display: flex;
    align-items: center;
    .text {
        margin-left: .6875rem;
    }
`


const Content = styled.div`
    width: 100%;
    height: 100%;
    /* min-height: calc(100% + 1px); // Keep scrolling enabled at all times to prevent closing the mini program when scrolling down. */
    display: flex;
    flex-direction: column;
`

const Inner = styled.div`
    flex: 1;
    padding: 0 1rem;
    padding-top: 1rem;
    box-sizing: border-box;
`

const CollectionView = styled.div`
    display: grid;
    grid-template-columns: repeat(2, 1fr); // 2 columns same width
    grid-template-rows: repeat(2, 5.625rem); 
    grid-row-gap: 1rem;
    grid-column-gap: 1rem;

`

const ActionBox = styled.div`
    display: flex;
    align-items: center;
    /* justify-content: center; */
    padding: 0 1rem;
    box-sizing: border-box;
    background-color: ${(prop) => prop.theme.background.box};
    border-radius: 1rem;
    position: relative;
`

const ActionBottom = styled.div`
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
`

const ActionContent = styled.div`
    display: flex;
    align-items: center;
`

const IconBox = styled(Icon)`
    width: 2rem;
    height: 2rem;
`

const Name = styled.span`
    font-weight: bold;
    font-size: .875rem;
    color: ${(prop) => prop.theme.text.normal};;
    margin-left: 11px;
`

const Wallet: React.FC = () => {
    const { t } = useTranslation()
    const dispatch = useDispatch();
    const navigate = useNavigate()

    const [loading, setLoading] = useState(false)
    const [data, setData] = useState<{ balance: number, balanceTon: number }>()

    const [config] = useSwitch()
    const showTon = useMemo(() => config.boolForKey(SwitchConfigKeys.TonWalletSwitch, false), [config])
    const showWithdraw = useMemo(() => config.boolForKey('withdraw', false), [config])

    useEffect(() => {
        const fetchData = async () => {
            setLoading(true)
            const result = await wallet();
            setLoading(false)
            if (!result.success || !result.data) {
                Message.error(result.message)
                return
            }
            result.data.image && dispatch(updateInfo({ icon: formatBase64Image(result.data.image) }))
            setData({ balance: Number(result.data.balance || 0), balanceTon: Number(result.data.balanceTon || 0) })
        }
        fetchData()
    }, [dispatch])

    const list = useMemo(() => {
        return [
            { title: t('wallet.coin.title'), sub: Number(data?.balance || 0).toFixed(3), $bg: WalletBg, tips: t('wallet.completed'), ton: Number(data?.balanceTon || 0).toFixed(3) }
        ]
    }, [t, data])

    const actions = useMemo(() => {
        const list = []
        list.push({ icon: 'wallet_pledge', title: t('wallet.action.pledge'), key: 'pledge' })
        list.push({ icon: 'wallet_trading', title: t('wallet.action.trade'), key: 'trade', bottom: <Trade /> })
        list.push({ icon: 'wallet_withdraw', title: t('wallet.action.withdraw'), key: 'withdraw' })
        list.push({ icon: 'wallet_deposit', title: t('wallet.action.deposit'), key: 'deposit' })

        return list
    }, [t])

    const onWithDrawClick = useCallback(async () => {
        navigate({
            pathname: Router.Withdraw,
            search: `?ton=${data?.balanceTon || 0}`,
        })
    }, [navigate, data?.balanceTon])

    const onClick = () => {
        Message.info(t('common.stayTuned'))
    }

    return <Container
        navigation={{
            title: <Title>{t('wallet.title')}</Title>
        }}
        hiddenSafeBottom={true}
        imagebackground={{
            image: IconBg,
            style: isIOS() ? {} : { position: 'fixed' } // TODO: why absolute will case some gesture problem in andriod
        }}
    >
        <Content>
            <Header>
                <User />
                {list.map((item, idx) => <BalanceBox key={idx}>
                    <ItemBox {...item} />
                    {showTon && <WithDrawBox>
                        <TonBox>
                            <Icon
                                name='ton_coin'
                                width='1.375rem'
                            />
                            <span className='text'>{item.ton}</span>
                        </TonBox>
                        {showWithdraw && <WithDraw onClick={onWithDrawClick}>{t('wallet.withdraw')}</WithDraw>}
                    </WithDrawBox>}
                </BalanceBox>)}
            </Header>
            <Inner>
                <CollectionView>
                    {actions.map((item) => <ActionBox
                        key={item.key}
                        onClick={onClick}
                    >
                        <ActionContent>
                            <IconBox name={item.icon} />
                            <Name>{item.title}</Name>
                        </ActionContent>
                        {item.bottom && <ActionBottom>{item.bottom}</ActionBottom>}
                    </ActionBox>)}
                </CollectionView>
            </Inner>
        </Content>
        <Loading show={loading} />
    </Container>
}
export default Wallet